﻿package cn.itamt.stars {
	import cn.itamt.stars.base.IStar;
	import cn.itamt.stars.base.StarStyle;

	import flash.display.DisplayObjectContainer;
	import flash.events.Event;
	import flash.geom.Rectangle;	

	/**
	 * @author tamt
	 */
	public class StarSystem {
		public static const STAR_TYPE_PLANET : String = 'planet_star';
		public static const STAR_TYPE_STATIC : String = 'static_star';

		private var container : DisplayObjectContainer;
		private var rect : Rectangle;

		public function StarSystem(container : DisplayObjectContainer, rect : Rectangle) {
			this.container = container;
			this.rect = rect;
			
			styles = [];
			movableStars = [];
		}

		private var styles : Array;

		public function addStarStyle(starType : String, rendererClass : Class, maxNum : uint = 50) : void {
			styles.push(new StarStyle(starType, rendererClass, maxNum));
		}

		private var isOn : Boolean = false;

		public function turnOn() : void {
			if(!isOn) {
				isOn = true;
				if(this.container.stage) {
					this.container.addEventListener(Event.REMOVED_FROM_STAGE, onContainerRemoved, false, 0, true);
					start();
				} else {
					this.container.addEventListener(Event.ADDED_TO_STAGE, onContainerAdded, false, 0, true);
				}
			}
		}

		private function onContainerAdded(evt : Event) : void {
			this.container.removeEventListener(Event.ADDED_TO_STAGE, onContainerAdded);
			if(isOn)start();
		}

		private function onContainerRemoved(evt : Event) : void {
			this.container.removeEventListener(Event.REMOVED_FROM_STAGE, onContainerRemoved);
			stop();
		}

		public function turnOff() : void {
			isOn = false;
			stop();
		}

		private function start() : void {
			this.container.addEventListener(Event.ENTER_FRAME, updateStars);
		}

		private function stop() : void {
			this.container.removeEventListener(Event.ENTER_FRAME, updateStars);
		}

		private var movableStars : Array;

		private function updateStars(evt : Event) : void {
			
			var style : StarStyle;
			var star : IStar;
			for(var i : int = 0;i < styles.length;i++) {
				style = styles[i];
				if(style.remainNum--) {
					star = style.buildStar(rect, this.container);
					if(style.starType == STAR_TYPE_PLANET) {
						movableStars.push(star);
					} else {
						star.update();
						star.render();
					}
				} else {
					styles.splice(i--, 1);
				}
			}
			
			var l : int = movableStars.length;
			for(i = 0;i < l; i++) {
				star = movableStars[i];
				star.update();
				star.render();
			}
		}

		public function dispose() : void {
			this.turnOff();
			
			this.container.removeEventListener(Event.ADDED_TO_STAGE, onContainerAdded);
			this.container.removeEventListener(Event.REMOVED_FROM_STAGE, onContainerRemoved);
		}
	}
}
